<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card" :body-style="{ 'min-height': 'calc(100vh - 150px)',padding: '20px' }">
          <div slot="header" class="clearfix">
            <span>角色信息</span>
          </div>
          <el-row>
            <el-col :span="24">
              <!-- query -->
              <el-form ref="roleQueryForm" :inline="true" :model="listQuery">
                <el-form-item label="角色名称" prop="roleName">
                  <el-input v-model="listQuery.roleName" clearable placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="角色编码" prop="roleCode">
                  <el-input v-model="listQuery.roleCode" clearable placeholder="请输入角色编码" />
                </el-form-item>
                <el-form-item label="角色类型" prop="roleType">
                  <el-select v-model="listQuery.roleType" clearable placeholder="请选择类型">
                    <el-option label="系统角色" value="1" />
                    <el-option label="普通角色" value="0" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
                  <el-button @click="resetForm('roleQueryForm')">重置</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-button type="primary" icon="el-icon-edit" @click="handleCreate">新增</el-button>
              <!-- table data -->
              <el-table
                v-loading="listLoading"
                :data="roleList"
                border
                fit
                highlight-current-row
                header-cell-class-name="table-header-cell"
                style="width: 100%; margin-top:10px;"
                @current-change="handleCurrentChange"
              >
                <el-table-column fixed label="选择" width="50" align="center">
                  <template slot-scope="scope">
                    <el-radio v-model="radio" class="radio" :label="scope.$index">&nbsp;</el-radio>
                  </template>
                </el-table-column>
                <el-table-column
                  fixed
                  prop="sId"
                  label="序号"
                  type="index"
                  width="100px"
                />
                <el-table-column
                  v-if="1>2"
                  prop="id"
                  label="角色ID"
                />
                <el-table-column
                  prop="roleName"
                  label="角色名称"
                />
                <el-table-column
                  prop="roleCode"
                  label="角色编码"
                />
                <el-table-column prop="roleType" label="角色类型">
                  <template slot-scope="scope">
                    <span>{{ scope.row.roleType | roleTypeFilter }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
                  <template slot-scope="{row}">
                    <el-button type="info" size="mini" @click.stop="handleUpdate(row)">修改</el-button>
                    <el-button type="danger" size="mini" @click.stop="handleDelete(row)">删除 </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination v-show="total>0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getList" />
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card" :body-style="{ 'min-height': 'calc(100vh - 150px)',padding: '20px' }">
          <div slot="header" class="clearfix">
            <span>角色用户信息</span>
          </div>
          <div v-if="userRoleQuery.roleId === ''">
            <div class="my-code">点击角色信息查看详情</div>
          </div>
          <div v-else>
            <el-row>
              <el-col :span="24">
                <!-- query -->
                <el-form ref="userRoleQueryForm" :inline="true" :model="userRoleQuery">
                  <el-form-item label="用户名称" prop="userName">
                    <el-input v-model="userRoleQuery.userName" clearable placeholder="请输入角色名称" />
                  </el-form-item>
                  <el-form-item label="用户编码" prop="userNo">
                    <el-input v-model="userRoleQuery.userNo" clearable placeholder="请输入角色编码" />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleUserFilter">查询</el-button>
                    <el-button @click="resetForm('userRoleQueryForm')">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-button type="primary" icon="el-icon-edit" @click="handleUserCreate">添加用户</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="handleUserDelete">删除用户</el-button>
                <el-table
                  ref="multipleUserTable"
                  v-loading="userListLoading"
                  :data="userList"
                  :row-key="getRowKeys"
                  border
                  fit
                  highlight-current-row
                  header-cell-class-name="table-header-cell"
                  style="width: 100%; margin-top:10px;"
                  empty-text="请选择角色信息"
                  @selection-change="handleUserSelectionChange"
                >
                  <el-table-column
                    type="selection"
                    width="45"
                    reserve-selection
                  />
                  <el-table-column
                    prop="sId"
                    label="序号"
                    type="index"
                    width="100px"
                  />
                  <el-table-column
                    v-if="1>2"
                    prop="userId"
                    label="用户ID"
                  />
                  <el-table-column
                    prop="userName"
                    label="用户名称"
                  />
                  <el-table-column
                    prop="userNo"
                    label="用户编码"
                  />
                </el-table>
                <pagination v-show="userListTotal>0" :total="userListTotal" :page.sync="userRoleQuery.current" :limit.sync="userRoleQuery.size" @pagination="getUserList" />
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- dialog -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="30%">
      <el-form ref="dataForm" :rules="rules" :model="roleTemp" label-position="left" label-width="90px" style="width: 80%; margin-left:50px;">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleTemp.roleName" clearable placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="roleTemp.roleCode" clearable placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="角色类型" prop="roleType">
          <el-select v-model="roleTemp.roleType" clearable placeholder="请选择类型">
            <el-option label="系统角色" value="1" />
            <el-option label="普通角色" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="新增角色用户" :visible.sync="dialogUserFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="50%" @close="closeAddUserRoleDialog">
      <div class="el-dialog-div">
        <!-- query -->
        <el-form ref="addUserRoleQueryForm" :inline="true" :model="addUserRoleQuery">
          <el-form-item label="用户名称" prop="userName">
            <el-input v-model="addUserRoleQuery.userName" clearable placeholder="请输入用户名称" />
          </el-form-item>
          <el-form-item label="用户编码" prop="userNo">
            <el-input v-model="addUserRoleQuery.userNo" clearable placeholder="请输入用户编码" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleRoleUserFilter">查询</el-button>
            <el-button @click="resetForm('addUserRoleQueryForm')">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table
          ref="multipleUserTable"
          v-loading="addUserRoleListLoading"
          :data="addUserRoleList"
          :row-key="getRowKeys"
          border
          fit
          header-cell-class-name="table-header-cell"
          style="width: 100%; margin-top:20px;"
          empty-text="暂无数据"
          @selection-change="handleRoleUserSelectionChange"
        >
          <el-table-column
            type="selection"
            width="45"
            reserve-selection
          />
          <el-table-column
            prop="sId"
            label="序号"
            type="index"
            width="100px"
          />
          <el-table-column
            v-if="1>2"
            prop="userId"
            label="用户ID"
          />
          <el-table-column
            prop="userName"
            label="用户名称"
          />
          <el-table-column
            prop="userNo"
            label="用户编码"
          />
        </el-table>
        <pagination v-show="roleUserListTotal>0" :total="roleUserListTotal" :page.sync="addUserRoleQuery.current" :limit.sync="addUserRoleQuery.size" @pagination="getAddUserRoles" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUserFormVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="createRoleUse">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'

import { fetchRoles, addRole, updateRole, deleteRole } from '@/api/role.js'
import { fetchUserRoles, fetchAddUserRoles, deleteUserRoles, addUserRole } from '@/api/user-role.js'

export default {
  name: 'RoleManagement',
  components: { Pagination },
  filters: {
    roleTypeFilter(roleType) {
      switch (roleType) {
        case '0':
          return '普通角色'
        case '1':
          return '系统角色'
      }
    }
  },
  data() {
    return {
      radio: '',
      total: 0,
      userListTotal: 0,
      roleUserListTotal: 0,
      listLoading: false,
      userListLoading: false,
      addUserRoleListLoading: false,
      roleList: [],
      userList: [],
      addUserRoleList: [],
      userSelectionList: [],
      roleUserSelectionList: [],
      listQuery: {
        current: 1,
        size: 10,
        roleCode: '',
        roleName: '',
        roleType: ''
      },
      userRoleQuery: {
        current: 1,
        size: 10,
        roleId: '',
        userName: '',
        userNo: ''
      },
      addUserRoleQuery: {
        current: 1,
        size: 10,
        roleId: '',
        userName: '',
        userNo: ''
      },
      dialogFormVisible: false,
      dialogUserFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      roleTemp: {
        roleCode: '',
        roleName: '',
        roleType: ''
      },
      rules: {
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'change' }],
        roleCode: [{ required: true, message: '角色编码不能为空', trigger: 'change' }],
        roleType: [{ required: true, message: '角色类型不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    resetRoleTemp() {
      this.roleTemp = {
        roleCode: '',
        roleName: '',
        roleType: ''
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    getRowKeys(row) {
      return row.id
    },
    clearMultipleUserTableSelection() {
      this.$refs.multipleUserTable.clearSelection()
      this.userSelectionList = []
    },
    getList() {
      this.listLoading = true
      fetchRoles(this.listQuery).then(response => {
        const res = response.retBody
        this.roleList = res.records
        this.total = res.total
      }).finally(() => {
        setTimeout(() => {
          this.listLoading = false
        }, 1 * 1000)
      })
    },
    getUserList() {
      if (!this.userRoleQuery.roleId) {
        this.$notify({
          title: '提示',
          message: '请先选择角色信息',
          type: 'warning',
          duration: 1500
        })
        return
      }

      this.userListLoading = true
      fetchUserRoles(this.userRoleQuery).then(response => {
        const res = response.retBody
        this.userList = res.records
        this.userListTotal = res.total
      }).finally(() => {
        setTimeout(() => {
          this.userListLoading = false
        }, 1 * 1000)
      })
    },
    getAddUserRoles() {
      this.addUserRoleListLoading = true
      fetchAddUserRoles(this.addUserRoleQuery).then(response => {
        const res = response.retBody
        this.addUserRoleList = res.records
        this.roleUserListTotal = res.total
      }).finally(() => {
        setTimeout(() => {
          this.addUserRoleListLoading = false
        }, 1 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
      this.userList = []
      this.userRoleQuery.roleId = ''
      this.userListTotal = 0
    },
    handleUpdate(row) {
      this.roleTemp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreate() {
      this.resetRoleTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('确定要删除该条角色信息?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除角色成功',
            type: 'success',
            duration: 1000
          })
          this.getList()
          this.getUserList()
        })
      }).catch(() => {

      })
    },
    handleCurrentChange(val) {
      this.radio = this.roleList.indexOf(val)
      if (val) {
        this.userRoleQuery.roleId = val.id
        this.addUserRoleQuery.roleId = val.id
        this.getUserList()
        this.clearMultipleUserTableSelection()
      }
    },
    handleUserFilter() {
      this.userRoleQuery.current = 1
      this.getUserList()
    },
    handleRoleUserFilter() {
      this.addUserRoleQuery.current = 1
      this.getAddUserRoles()
    },
    handleUserCreate() {
      if (!this.userRoleQuery.roleId) {
        this.$notify({
          title: '提示',
          message: '请先选择角色信息',
          type: 'warning',
          duration: 1500
        })
        return
      }
      this.dialogUserFormVisible = true
      this.addUserRoleQuery.current = 1
      this.getAddUserRoles()
    },
    handleUserSelectionChange(val) {
      this.userSelectionList = val
    },
    handleRoleUserSelectionChange(val) {
      this.roleUserSelectionList = val
    },
    handleUserDelete() {
      if (!this.userSelectionList || this.userSelectionList.length === 0) {
        this.$notify({
          title: '提示',
          message: '未选择相关用户信息',
          type: 'warning',
          duration: 1500
        })
        return
      }

      this.$confirm('确定要删除选中的用户信息?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const userRoleIds = this.userSelectionList.map(item => {
          return item.id
        })
        const ids = {}
        ids.userRoleIds = userRoleIds.join(',')
        deleteUserRoles(ids).then(() => {
          this.$notify({
            title: '成功',
            message: '删除角色用户成功',
            type: 'success',
            duration: 1000
          })
          this.clearMultipleUserTableSelection()
          this.userRoleQuery.current = 1
          this.getUserList()
        })
      }).catch(() => {

      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addRole(this.roleTemp).then(() => {
            // this.roleList.unshift(this.roleTemp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新增角色成功',
              type: 'success',
              duration: 1000
            })
            this.getList()
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateRole(this.roleTemp.id, this.roleTemp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改角色信息成功',
              type: 'success',
              duration: 1000
            })
            this.getList()
          })
        }
      })
    },
    createRoleUse() {
      if (this.roleUserSelectionList && this.roleUserSelectionList.length > 0) {
        const roleUserRoleIds = this.roleUserSelectionList.map(item => {
          return item.userId
        })
        const addRoleUsers = {}
        addRoleUsers.roleId = this.userRoleQuery.roleId
        addRoleUsers.userIds = roleUserRoleIds
        addUserRole(addRoleUsers).then(() => {
          this.dialogUserFormVisible = false
          this.$notify({
            title: '成功',
            message: '新增角色用户成功',
            type: 'success',
            duration: 1000
          })
          this.getUserList()
        })
      } else {
        this.dialogUserFormVisible = false
      }
    },
    closeAddUserRoleDialog() {
      this.addUserRoleQuery.userName = ''
      this.addUserRoleQuery.userNo = ''
      this.roleUserSelectionList = []
      this.$refs.multipleUserTable.clearSelection()
    }
  }
}
</script>
<style scoped>
.el-dialog-div{
  height: 60vh;
  overflow: auto;
}
 .my-code{
    padding: 15px;
    line-height: 20px;
    border-left: 3px solid #ddd;
    color: #333;
    font-family: Courier New;
    font-size: 16px
  }
</style>
